package cn.yuanqiao.archive.archiveBorrowCar.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantFields;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantFieldsMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.archiveBorrowCar.domain.YqdaborrowCar;
import cn.yuanqiao.archive.archiveBorrowCar.mapper.YqdaborrowCarMapper;
import cn.yuanqiao.archive.archiveBorrowCar.service.IYqdaborrowCarService;
import cn.yuanqiao.archive.liyong.domain.AppointmentForm;
import cn.yuanqiao.archive.liyong.mapper.AppointmentFormMapper;
import cn.yuanqiao.archive.liyong.service.IAppointmentFormService;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * archiveBorrowCarService业务层处理
 *
 * @author yuanqiao
 * @date 2023-07-14
 */
@Service
public class YqdaborrowCarServiceImpl implements IYqdaborrowCarService
{
    @Autowired
    private YqdaborrowCarMapper yqdaborrowCarMapper;

    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private TenantMdataListMapper tenantMdataListMapper;

    @Autowired
    private AppointmentFormMapper appointmentFormMapper;
    @Autowired
    private IAppointmentFormService appointmentFormService;

    /**
     * 查询archiveBorrowCar
     *
     * @param carId archiveBorrowCar主键
     * @return archiveBorrowCar
     */
    @Override
    public YqdaborrowCar selectYqdaborrowCarByCarId(String carId)
    {
        return yqdaborrowCarMapper.selectYqdaborrowCarByCarId(carId);
    }

    /**
     * 查询archiveBorrowCar列表
     *
     * @param yqdaborrowCar archiveBorrowCar
     * @return archiveBorrowCar
     */
    @Override
    public List<YqdaborrowCar> selectYqdaborrowCarList(YqdaborrowCar yqdaborrowCar)
    {
        return yqdaborrowCarMapper.selectYqdaborrowCarList(yqdaborrowCar);
    }

    /**
     * 新增archiveBorrowCar
     *
     * @param yqdaborrowCar archiveBorrowCar
     * @return 结果
     */
    @Override
    public int insertYqdaborrowCar(YqdaborrowCar yqdaborrowCar)
    {
        yqdaborrowCar.setCarId(String.valueOf(SnowflakeIdGenerator.generateId()));
        return yqdaborrowCarMapper.insertYqdaborrowCar(yqdaborrowCar);
    }

    /**
     * 修改archiveBorrowCar
     *
     * @param yqdaborrowCar archiveBorrowCar
     * @return 结果
     */
    @Override
    public int updateYqdaborrowCar(YqdaborrowCar yqdaborrowCar)
    {
        return yqdaborrowCarMapper.updateYqdaborrowCar(yqdaborrowCar);
    }

    /**
     * 批量删除archiveBorrowCar
     *
     * @param carIds 需要删除的archiveBorrowCar主键
     * @return 结果
     */
    @Override
    public int deleteYqdaborrowCarByCarIds(String[] carIds)
    {
        return yqdaborrowCarMapper.deleteYqdaborrowCarByCarIds(carIds,SecurityUtils.getUserId(),SecurityUtils.getTenantCode());
    }

    /**
     * 批量删除archiveBorrowCar
     *
     * @param archiveIds 需要删除的archiveBorrowCar档案id
     * @return 结果
     */
    @Override
    public int deleteYqdaborrowCarByArchiveIds(String[] archiveIds)
    {
        return yqdaborrowCarMapper.deleteYqdaborrowCarByArchiveIds(archiveIds,SecurityUtils.getUserId(),SecurityUtils.getTenantCode());
    }

    /**
     * 删除archiveBorrowCar信息
     *
     * @param carId archiveBorrowCar主键
     * @return 结果
     */
    @Override
    public int deleteYqdaborrowCarByCarId(String carId)
    {
        return yqdaborrowCarMapper.deleteYqdaborrowCarByCarId(carId);
    }



    @Override
    public List<Map<String, Object>> selectArchiveByArchiveIdAndCategoryId(String archiveIds) {
        StringBuilder sqlBulider = new StringBuilder();
        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        //String tenantCode = "DDDD";
        //查询公共字段
        /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
        TenantFields tenantField = new TenantFields();
        tenantField.setIsCommon("1");
        tenantField.setState("1");
        List<TenantFields> tenantFields = tenantFieldsMapper.selectTenantFieldsList(tenantField);
        StringBuilder fieldCommon = new StringBuilder();
        Set<String> yqdaFields = new HashSet<>();
        Set<String> yqfolderFields = new HashSet<>();
        Set<String> yqItemFields = new HashSet<>();
        for (TenantFields item : tenantFields) {
            if ("0".equals(item.getType())) {
                yqdaFields.add(item.getFieldName());
            } else if ("1".equals(item.getType())) {
                yqfolderFields.add(item.getFieldName());
            }else if ("3".equals(item.getType())) {
                yqItemFields.add(item.getFieldName());
            }

        }
        /*Set<String> commonFields = new HashSet<>(yqdaFields);
        commonFields.retainAll(yqfolderFields);
        for (String element : commonFields) {
            fieldCommon.append(element).append(",");
        }*/

        //fieldCommon.deleteCharAt(fieldCommon.length()-1);
        /*sqlBulider.append("SELECT ").append(fieldCommon).append("'0' AS DA_TYPE,DA_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                .append("_CATEGORY WHERE FILE_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ").append(" FROM ").append(tenantCode)
                .append("_YQDA WHERE DA_ID IN(").append(archiveIds).append(") UNION ALL SELECT ").append(fieldCommon)
                .append("'1' AS DA_TYPE,FOLDER_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                .append("_CATEGORY WHERE FOLDER_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ")
                .append("  FROM ").append(tenantCode).append("_YQFOLDER AS ID WHERE FOLDER_ID IN(").append(archiveIds).append(");");*/
        /*sqlBulider.append("SELECT ").append(fieldCommon).append("'0' AS DA_TYPE,DA_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                .append("_CATEGORY WHERE FILE_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ").append(" FROM ").append(tenantCode)
                .append("_YQDA WHERE DA_ID IN(").append(archiveIds).append(") UNION ALL SELECT ").append(fieldCommon)
                .append("'1' AS DA_TYPE,FOLDER_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                .append("_CATEGORY WHERE FOLDER_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ")
                .append("  FROM ").append(tenantCode).append("_YQFOLDER WHERE FOLDER_ID IN(").append(archiveIds).append(") UNION ALL SELECT ")
                .append(fieldCommon).append("'2' AS DA_TYPE,ITEM_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                .append("_CATEGORY WHERE ITEM_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ")
                .append("  FROM ").append(tenantCode).append("_YQITEM WHERE ITEM_ID IN(").append(archiveIds).append(");");*/
        //List<Map<String, Object>> maps = yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId( sqlBulider.toString());
        StringBuilder sqlFileBulider = new StringBuilder();
        StringBuilder sqlFolderBulider = new StringBuilder();
        StringBuilder sqlItemBulider = new StringBuilder();
        sqlFileBulider.append("SELECT ").append(StringUtils.join(yqdaFields,',')).append(",'0' AS DA_TYPE,DA_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                .append("_CATEGORY WHERE FILE_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ").append(" FROM ").append(tenantCode)
                .append("_YQDA WHERE DA_ID IN(").append(archiveIds).append(");");
        List<Map<String, Object>> fileMap = yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId(sqlFileBulider.toString());
        sqlFolderBulider.append(" SELECT ").append(StringUtils.join(yqfolderFields,',')).append(",'1' AS DA_TYPE,FOLDER_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                .append("_CATEGORY WHERE FOLDER_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ")
                .append("  FROM ").append(tenantCode).append("_YQFOLDER WHERE FOLDER_ID IN(").append(archiveIds).append(");");
        List<Map<String, Object>> folderMap = yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId(sqlFolderBulider.toString());

        sqlItemBulider.append("SELECT ").append(StringUtils.join(yqItemFields,',')).append(",'3' AS DA_TYPE,ITEM_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ")
                .append(tenantCode)
                .append("_CATEGORY WHERE ITEM_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ")
                .append("  FROM ").append(tenantCode).append("_YQITEM WHERE ITEM_ID IN(").append(archiveIds).append(");");
        List<Map<String, Object>> itemMap = yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId(sqlItemBulider.toString());
        fileMap.addAll(folderMap);
        fileMap.addAll(itemMap);
        //List<Map<String, Object>> maps = yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId( sqlBulider.toString())
        return fileMap;
    }

    @Override
    public List<Map<String, Object>> selectArchiveByArchiveIdAndCategoryIdMap(Map<Long,List<String>> map) {

        String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
        List<Map<String, Object>> returnMap = new ArrayList<>();
        for (Map.Entry<Long, List<String>> entrySet : map.entrySet()) {
            Long categoryId = entrySet.getKey();
            List<String> archiveIds = entrySet.getValue();
            List<TenantMdataList> tenantMdataListListByCategoryId = tenantMdataListMapper.selectTenantMdataListListByCategoryId(new TenantMdataList(), categoryId, tenantCode + "_CATEGORY");
            Set<String> yqdaFields = new HashSet<>();
            Set<String> yqfolderFields = new HashSet<>();
            Set<String> yqItemFields = new HashSet<>();
            for (TenantMdataList item : tenantMdataListListByCategoryId) {
                if (Integer.valueOf(0).equals(item.getType())) {
                    yqdaFields.add(item.getFieldName());
                } else if (Integer.valueOf(1).equals(item.getType())) {
                    yqfolderFields.add(item.getFieldName());
                }else if (Integer.valueOf(3).equals(item.getType())) {
                    yqItemFields.add(item.getFieldName());
                }
            }
            StringBuilder sqlFileBulider = new StringBuilder();
            StringBuilder sqlFolderBulider = new StringBuilder();
            StringBuilder sqlItemBulider = new StringBuilder();
            if (yqdaFields.size()!=0){
                sqlFileBulider.append("SELECT ").append(StringUtils.join(yqdaFields,',')).append(",'f' AS DA_TYPE,DA_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                        .append("_CATEGORY WHERE FILE_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ").append(" FROM ").append(tenantCode)
                        .append("_YQDA WHERE DA_ID IN(").append(StringUtils.join(archiveIds,",")).append(");");
                returnMap.addAll(yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId(sqlFileBulider.toString()));
            }
            if (yqfolderFields.size()!=0){
                sqlFolderBulider.append(" SELECT ").append(StringUtils.join(yqfolderFields,',')).append(",'v' AS DA_TYPE,FOLDER_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ").append(tenantCode)
                        .append("_CATEGORY WHERE FOLDER_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ")
                        .append("  FROM ").append(tenantCode).append("_YQFOLDER WHERE FOLDER_ID IN(").append(StringUtils.join(archiveIds,",")).append(");");
                returnMap.addAll(yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId(sqlFolderBulider.toString()));
            }
            if (yqItemFields.size()!=0){
                sqlItemBulider.append("SELECT ").append(StringUtils.join(yqItemFields,',')).append(",'x' AS DA_TYPE,ITEM_ID AS ID,SUB_TABLE_NAME,(SELECT ID FROM ")
                        .append(tenantCode)
                        .append("_CATEGORY WHERE ITEM_TABLE_NAME = SUB_TABLE_NAME) AS CATEGORY_ID ")
                        .append("  FROM ").append(tenantCode).append("_YQITEM WHERE ITEM_ID IN(").append(StringUtils.join(archiveIds,",")).append(");");
                returnMap.addAll(yqdaborrowCarMapper.selectArchiveByArchiveIdAndCategoryId(sqlItemBulider.toString()));
            }
        }

        return returnMap;
    }

    @Override
    public int batchInsertYqdaborrowCar(List<YqdaborrowCar> yqdaborrowCars) {
        for (YqdaborrowCar yc : yqdaborrowCars) {
            if (yc.getDaType().equals("F")) {
                String tableName = yc.getArchiveType().equals("f") ? Constants.BIG_TABLE_YQDA : yc.getArchiveType().equals("v") ? Constants.BIG_TABLE_YQFOLDER : Constants.BIG_TABLE_YQITEM;
                String id = yc.getArchiveType().equals("f") ? "da_id" : yc.getArchiveType().equals("v") ? "FOLDER_ID" : "ITEM_ID";
                List<Map<String, Object>> daList = appointmentFormMapper.selectList(" STJSFJC,IS_APPOINTMENT ", " select STJSFJC,IS_APPOINTMENT from " + SecurityUtils.getTenantCode() + tableName +
                        " where " + id + " =" + yc.getDaId());
                if (daList != null && daList.size() > 0 && daList.get(0)!=null) {
                    String isappointment = String.valueOf(daList.get(0).get("IS_APPOINTMENT"));
                    String stjsfjc = String.valueOf(daList.get(0).get("STJSFJC"));
                    //  1 已预约  已借阅    0  未预约   未借阅
                    if ("1".equals(stjsfjc)) {
                        throw new ServiceException("当前档案已经被借阅!");
                    }
                    if ("1".equals(isappointment)) {
                        int i = appointmentFormMapper.selectAppointmentFormByDaId(yc.getDaId(), new AppointmentForm().getTableName(), String.valueOf(SecurityUtils.getUserId()));
                        if (i < 1) {
                            throw new ServiceException("当前档案已经被预约!");
                        }
                    }
                }
            }
        }
        return yqdaborrowCarMapper.batchInsertYqdaborrowCar(yqdaborrowCars);
    }

    @Override
    public boolean checkArchiveIsAddCar(List<YqdaborrowCar> yqdaborrowCars) {
        int i = yqdaborrowCarMapper.checkArchiveIsAddCar( yqdaborrowCars);
        return i==0?false:true;
    }

    @Override
    public List<YqdaborrowCar> selectYqdaborrowCarListByIds(YqdaborrowCar yqdaborrowCar) {
        return yqdaborrowCarMapper.selectYqdaborrowCarListByIds(yqdaborrowCar);
    }

    /**
     * 判断能否借阅
     * @param yqdaborrowCars
     * @return
     */
    @Override
    public boolean judgeborrow(List<YqdaborrowCar> yqdaborrowCars) {
        for (YqdaborrowCar yc : yqdaborrowCars) {
            if (yc.getDaType().equals("F")) {
                String tableName = yc.getArchiveType().equals("f") ? Constants.BIG_TABLE_YQDA : yc.getArchiveType().equals("v") ? Constants.BIG_TABLE_YQFOLDER : Constants.BIG_TABLE_YQITEM;
                String id = yc.getArchiveType().equals("f") ? "da_id" : yc.getArchiveType().equals("v") ? "FOLDER_ID" : "ITEM_ID";
                //达梦数据获取STJSFJC,IS_APPOINTMENT字段为空值时， 311行报错 所以补充 id查询字段
                List<Map<String, Object>> daList = appointmentFormMapper.selectList(" STJSFJC,IS_APPOINTMENT,"+id+" ", " select STJSFJC,IS_APPOINTMENT,"+id+" from " + SecurityUtils.getTenantCode() + tableName +
                        " where " + id + " =" + yc.getDaId());
                if (daList != null && daList.size() > 0) {
                    String isappointment = String.valueOf(daList.get(0).get("IS_APPOINTMENT"));
                    String stjsfjc = String.valueOf(daList.get(0).get("STJSFJC"));
                    //  1 已预约  已借阅    0  未预约   未借阅
                    if ("1".equals(stjsfjc)) {
                        return true;
                    }
                    if ("1".equals(isappointment)) {
                        List<AppointmentForm> appointmentForms = appointmentFormMapper.selectAppointmentFormByDaIdList(yc.getDaId(),
                                "0", new AppointmentForm().getTableName(), String.valueOf(SecurityUtils.getUserId()),null);
                        if (appointmentForms != null && appointmentForms.size()> 0) {
                            String ids = appointmentForms.stream().distinct().map(m -> String.valueOf(m.getId())).collect(Collectors.joining("','"));
                            AppointmentForm af= appointmentForms.get(0);
                            appointmentFormMapper.updateTableData("update "+new AppointmentForm().getTableName()+" set STATUS = 2 where id in ('"+ids+"')");
                            appointmentFormService.updateData(yc.getDaId(),af.getDaType(),af.getSubTableName(),0);
                            return false;
                        } else {
                            return true;
                        }
                    }
                }
            }
        }
        return  false;
    }


    @Override
    public List<Map<String, Object>> getArchiveListByArchiveCategory(YqdaborrowCar yqdaborrowCar) {
        yqdaborrowCar.setSTATUS("1");
        yqdaborrowCar.setUserId(String.valueOf(SecurityUtils.getUserId()));
        yqdaborrowCar.setTenantCode(SecurityUtils.getTenantCode());
        List<YqdaborrowCar> yqdaborrowCars = selectYqdaborrowCarList(yqdaborrowCar);
        if (yqdaborrowCars.size()==0){
            return null;
        }
        Map<Long,Map<String,List<YqdaborrowCar>>> carMap = new HashMap<>();
        yqdaborrowCars.forEach(item->{
            Long categoryId = item.getCategoryId();
            if (carMap.get(categoryId) == null){
                Map<String,List<YqdaborrowCar>> map = new HashMap<>();
                List<YqdaborrowCar> list = new ArrayList<>();
                list.add(item);
                map.put(item.getArchiveType(),list);
                carMap.put(categoryId,map);
            }else {
                if (carMap.get(categoryId).get(item.getArchiveType())==null){
                    List<YqdaborrowCar> list = new ArrayList<>();
                    list.add(item);
                    carMap.get(categoryId).put(item.getArchiveType(),list);
                    /*carMap.put(categoryId,map);*/
                }else {
                    carMap.get(categoryId).get(item.getArchiveType()).add(item);
                }
            }
        });
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Map.Entry<Long,Map<String,List<YqdaborrowCar>>> entry:carMap.entrySet()) {
            Long categoryId = entry.getKey();
            Map<String,List<YqdaborrowCar>> daTypeMap = entry.getValue();
            for (Map.Entry<String,List<YqdaborrowCar>> listEntry : daTypeMap.entrySet()){
                String archiveType = listEntry.getKey();
                List<YqdaborrowCar> value = listEntry.getValue();
                Map<String,String> idDaType = new HashMap<String,String>();
                for (YqdaborrowCar item : value) {
                    idDaType.put(item.getDaId(),item.getDaType());
                }
                YqdaborrowCar tempData = value.get(0);
                String daType = tempData.getDaType();
                StringBuilder sqlBulider = new StringBuilder();
                String tenantCode = SecurityUtils.getTenantCode().toUpperCase();
                //String tenantCode = "DDDD";
                //查询公共字段
                /*List<Map<String,Object>> commonFileds = yqdaborrowCarMapper.selectCommonFiledByTenantCode( tenantCode);*/
                TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, tenantCode + "_CATEGORY");
                String name = tenantCategory.getName();

                Integer type = tenantCategory.getType();
                String tableName = null;
                /*if (type==0){
                    tableName = tenantCategory.getFileTableName();
                }else if (type==1){
                    tableName = tenantCategory.getFolderTableName();
                }else if (type==3){
                    tableName = tenantCategory.getItemTableName();
                }*/
                if ("f".equals(archiveType)){
                    tableName = tenantCategory.getFileTableName();
                }else if ("v".equals(archiveType)){
                    tableName = tenantCategory.getFolderTableName();
                }else if ("x".equals(archiveType)){
                    tableName = tenantCategory.getItemTableName();
                }

                TenantMdataList tenantMdataList = new TenantMdataList();
                tenantMdataList.setIsHidden(0);
                //List<TenantMdataList> tenantMdataLists = tenantMdataListMapper.selectTenantMdataListListByCategoryId(tenantMdataList, categoryId, tenantCode + "_CATEGORY");

                //StringBuilder fieldCommon = new StringBuilder();
                StringBuilder archiveIdBuilder = new StringBuilder();
                value.forEach(item->archiveIdBuilder.append(item.getDaId()).append(","));
                //FIXME 测试用字段
                //tenantMdataLists.forEach(item->fieldCommon.append(item.getFieldName()).append(","));
                //fieldCommon.append("*,");


                archiveIdBuilder.deleteCharAt(archiveIdBuilder.length()-1);
                String archiveIds = archiveIdBuilder.toString();
                //fieldCommon.deleteCharAt(fieldCommon.length()-1);
                sqlBulider.append("SELECT ").append("*,").append(categoryId).append(" AS CATEGORY_ID,'").append(archiveType)
                        .append("' AS DA_TYPE ,'").append(tempData.getDaType()).append("' as BORROW_TYPE, '").append(tableName).append("' AS SUB_TABLE_NAME FROM ").append(tableName).append(" WHERE ID IN(").append(archiveIds).append(")");
                List<Map<String, Object>> maps = yqdaborrowCarMapper.selectYqdaArchiveList(sqlBulider.toString());
                for (Map<String, Object> item : maps) {
                    item.put("BORROW_TYPE",idDaType.get(String.valueOf(item.get("ID"))));
                    item.put("DAML",name);

                }
                mapList.addAll(maps);

            }
        }
        return mapList;
    }
}
